package com.java.file.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.utils.CopyUtil;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.common.utils.UuidUtil;
import com.java.file.dao.FileDao;
import com.java.file.entity.FileEntity;
import com.java.file.service.FileService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service("fileService")
public class FileServiceImpl extends ServiceImpl<FileDao, FileEntity> implements FileService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<FileEntity> page = this.page(
                new Query<FileEntity>().getPage(params),
                // 拼接查询条件
                new LambdaQueryWrapper<FileEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateOrSave(FileEntity fileEntity) {
        FileEntity fileDb = selectByKey(fileEntity.getKey());
        if (fileDb == null) {
            fileEntity.setId(UuidUtil.getShortUuid());
            this.save(fileEntity);
        } else {
            fileDb.setShardIndex(fileEntity.getShardIndex());
            this.updateById(fileDb);
        }
    }

    @Override
    public FileEntity selectByKey(String key) {
        List<FileEntity> fileEntities = this.baseMapper.selectList(new LambdaQueryWrapper<FileEntity>().eq(FileEntity::getKey, key));
        if (CollectionUtil.isEmpty(fileEntities)) {
            return null;
        } else {
            return fileEntities.get(0);
        }
    }

}